package com.loie.xcx.web.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.loie.xcx.mapper.SqlMapper;
import com.loie.xcx.model.bankdto.Pf_notifiy_loanBO;
import com.loie.xcx.model.bankdto.PftypeBO;


import com.loie.xcx.model.bankdto.ResultDTO;
import com.loie.xcx.model.bankdto.Shbank_OrdrRgst;
import com.loie.xcx.model.dto.ApplyPaymentDTO;
import com.loie.xcx.service.FkblService;
import com.loie.xcx.syUtil.HttpUtil;


import com.loie.xcx.util.ErrorMessage;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public
@Controller
@RequestMapping("/SHAPI")
class Shbank_Api {
    Logger logger = LoggerFactory.getLogger(getClass());
    private static final Logger paramLogger = LoggerFactory.getLogger("banklog");
    //Logger paramLogger = LoggerFactory.getLogger("SHparamLogger");
    private String CHANNEL = "bosc-qcjj";
    private String urlPrefix = "https://bosccloud.qhhrly.cn/cloud/std";


    private String urlPrefixPrd = "https://bosccloud.weqchain.com/cloud/std";;
    @Autowired
   FkblService fkblService;

    @Autowired
    SqlMapper sqlMapper;


    @RequestMapping(value = "/SendToSpdb/{action}", method = RequestMethod.POST)
    @ResponseBody
    public
    String providersApi(@RequestParam String msg, @PathVariable String action) {

            String ret = "";
            String logUuid = UUID.randomUUID().toString().toLowerCase();
            try {
                paramLogger.info(logUuid + ":[" + action + "]in-->" + msg);
                ret = doQuery(msg, action, logUuid);
                return ret;
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(logUuid + ":[" + action + "]error-->" + msg, e);
                ret = JSON.toJSONString(new ResultDTO(logUuid, ErrorMessage.ERR_SYSTEM, ErrorMessage.ERROR));
                return ret;
            } finally {
                paramLogger.info(logUuid + ":[" + action + "]out-->" + ret);
            }
        }
    private
    String doQuery(String msg, String action, String logUuid) throws Exception {
        String ret = "";
        try {
            String url = null;
            switch (action) {
                case "importAssetInfo":
                    url =urlPrefixPrd + "/ast/importAssetInfo";
                    break;
                case "queryAssetStatus":
                    url = urlPrefixPrd + "/ast/queryAssetStatus";
                    break;
                case "ordLndStQry":
                    url = "https://etest4.spdb.com.cn/spdb/uat/api/cmpyLoan/ordLndStQry";
                    break;
                case "olBrwLmtQry":
                    url = "https://etest4.spdb.com.cn/spdb/uat/api/cmpyLoan/olBrwLmtQry";
                    break;
                case "queryStdDuePayResult":
                    url = urlPrefixPrd + "/ast/queryStdDuePayResult";;
                    break;
                default:
                    ret = JSON.toJSONString(new ResultDTO(logUuid, ErrorMessage.ERR_INVAILD_REQ, ErrorMessage.ERROR));
                    return ret;
            }

            if (action.equals("importAssetInfo")) {
                if (msg != null) {
                    JSONObject json = JSONObject.parseObject(msg);
                    String orderNum = json.getString("orderNum");
                    String billNotifyNo = json.getString("billNotifyNo");
                    paramLogger.info("");
                    Shbank_OrdrRgst voOrdrRgst = fkblService.getshbank_yforder(orderNum, billNotifyNo);
                   // System.out.println(voOrdrRgst);
                    //System.exit(0);
                    ret = HttpUtil.postObject(CHANNEL, voOrdrRgst, false, false, url, UUID.randomUUID().toString());
                    json = JSONObject.parseObject(ret);
                    String statusCode = json.getString("code");
                    Integer i=0;
                    if (statusCode.equals("200")) {
                        String statusMsg = json.getString("msg");
                        JSONObject rplyRslt = json.getJSONObject("data");
                        String sourceAssetNo = rplyRslt.getString("sourceAssetNo");
                        String importSerialNo = rplyRslt.getString("serialNo");
                        i= fkblService.updateshbank_OrdrRgst_state(orderNum, "申请中",statusMsg,sourceAssetNo,importSerialNo);

                    } else {
                        String statusMsg = json.getString("msg");
                        i=fkblService.updateshbank_OrdrRgst_state(orderNum,"审核未过", statusMsg,"","");
                    }
                    if (i>0) {json.put("savestate","保存成功");}
                    else {json.put("savestate","保存失败");}
                    ret=json.toJSONString();
//
                }
            }
            else if (action.equals("queryStdDuePayResult")){
                if (msg != null) {
                    JSONObject json = JSONObject.parseObject(msg);
                    paramLogger.info("资产兑付接口发送-" + msg);

                    String orderNum = json.getString("sourceAssetNo");
                    //System.out.println(orderNum);
                    String result = HttpUtil.postObject(CHANNEL, json, false, false, url, UUID.randomUUID().toString());
                    json = JSONObject.parseObject(result);
                    ret = json.toJSONString();
                    System.out.println("资产兑付接口回复:" + ret);
                }

            }
            else if  (action.equals("queryAssetStatus")) {
                if (msg != null) {
                    JSONObject json = JSONObject.parseObject(msg);
                    paramLogger.info(msg);

                    String orderNum = json.getString("sourceAssetNo");
                    //System.out.println(orderNum);
                    String result = HttpUtil.postObject(CHANNEL, json, false, false, url, UUID.randomUUID().toString());
                    //System.out.println("资料查询结果:" + result);
                    json = JSONObject.parseObject(result);
                    ret = json.toJSONString();
                    System.out.println("解密数据:" + ret);
                    String statusCode = json.getString("code");
                    Integer i = 0;

                    if (statusCode.equals("200")) {
                        String statusMsg = json.getString("msg");
                        String rejectReason = "";
                        String checkstr = "";
                        String tsAssetId = "";
                        JSONObject rplyRslt = json.getJSONObject("data");
                        if (rplyRslt.containsKey("rejectReason")) {
                            rejectReason = rplyRslt.getString("rejectReason");
                        }
                        if (rplyRslt.containsKey("tsAssetId")) {
                            tsAssetId = rplyRslt.getString("tsAssetId");
                        }
                        JSONObject statejson = rplyRslt.getJSONObject("status");
                        String state = statejson.getString("displayName");
                        if (state.equals("已上链")) {
                            //state = "审核通过";
                            checkstr = "数字资产编号:" + tsAssetId;
                        } else {
                            //if (checkstr != null && !checkstr.isEmpty())
                            if (rejectReason!= null && !rejectReason.isEmpty())
                                checkstr = "退回原因" + rejectReason;
                        }

                        //System.out.println(checkstr);
                        Map<String, Object> params = new HashMap<>();
                        params.clear();
                        params.put("sql", "select applyno from shbank_OrdrRgst where  sourceAssetNo=#{sourceAssetNo} ");

                        params.put("sourceAssetNo", orderNum);
                        String Applyno =sqlMapper.dic_type(params);
                        i = fkblService.updateshbank_OrdrRgst_checkstate(orderNum, state, checkstr);
//                        ApplyPaymentDTO applyPaymentDTO=new ApplyPaymentDTO();
//                        if (!StringUtils.isBlank(Applyno)){
//                        applyPaymentDTO.setApplyNo(Applyno);
//                        applyPaymentDTO.setShbankstate(state);
//                        fkblService.update_applypayment_fkzt(applyPaymentDTO);
//                        paramLogger.info("更新付款通知，单号:"+Applyno+"-上海银行审核状态:"+state);
//                        };


                        System.out.println(i);

                    }
                }


            }


        }
     catch (Exception e) {
        e.printStackTrace();
        logger.error(logUuid + ":error-->" + JSON.toJSONString(msg), e);
        ret = JSON.toJSONString(new ResultDTO(logUuid, ErrorMessage.ERR_SYSTEM, ErrorMessage.ERROR));
    }

        return ret;
    }
    /**
     * 上银调用
     *
     * @param msg String
     * @return String
     */
    @RequestMapping(value = "/handle", method = RequestMethod.POST)
    @ResponseBody
    public String handleBusiness(@RequestBody String msg) throws Exception {
        String ret = null;
        //String ret1 = null;
        //记录
        paramLogger.info("in-->" + msg);
        String requestId = "0001";
        try {
            String data=HttpUtil.decode_key(CHANNEL,msg,false,"");
            paramLogger.info("解密数据:" + data);

            String code = "0000";
            String resultMsg = "接收成功";
            JSONObject resultData = new JSONObject();
            //resultData.put("projectId", 6625325769688092672L);
            //resultData.put("coreCompanyName", data);
            resultData.put("code", code);
            resultData.put("msg", resultMsg);

             ret = HttpUtil.encode_key(CHANNEL, resultData, false, false, "", UUID.randomUUID().toString());
            //9. 返回
            //ret = JSONObject.parseObject(result);
                    //JSONUtils.toJSONString(result);

            //处理获取数据并保存到放款通知表中
            //ret = new ResultDTO("123");
            //更新放款通知

            if (data != null) {
                JSONObject json = JSONObject.parseObject(data);
                Pf_notifiy_loanBO FkdlShjg = JSON.toJavaObject(json, Pf_notifiy_loanBO.class);
                System.out.println(FkdlShjg);
                Map<String, Object> params = new HashMap<>();
                if (FkdlShjg != null) {
                    try {


                        //Double rate=1.00;
                        params.clear();
                        params.put("sql", "select CustomerCorpName from shbank_OrdrRgst where  sourceAssetNo=#{sourceAssetNo} ");
                        //params.put("orderNo", FkdlShjg.getOrderNum());
                        params.put("sourceAssetNo", FkdlShjg.getOrderSeqNo());
                        String suppliername =sqlMapper.dic_type(params);
                        //String suppliername = fkblService.selectcontext("select CustomerCorpName from shbank_OrdrRgst where orderNo=?", FkdlShjg.getOrderNum());
                        FkdlShjg.setCustomerCorpName(suppliername);
                    }catch (Exception e) {
                        FkdlShjg.setCustomerCorpName(json.get("supplierCorpName").toString());}


                    FkdlShjg.setBankname("上海银行");
                    try{
                        params.clear();
                        params.put("sql", "select ApplyNo from shbank_OrdrRgst where  sourceAssetNo=#{sourceAssetNo} ");
                        //params.put("orderNo", FkdlShjg.getOrderNum());
                        params.put("sourceAssetNo", FkdlShjg.getOrderSeqNo());
                        String ApplyNo =sqlMapper.dic_type(params);

                        //String ApplyNo = fkblService.selectcontext("select ApplyNo from shbank_OrdrRgst where orderNo=?", FkdlShjg.getOrderNum());
                        FkdlShjg.setApplyNo(ApplyNo);}
                    catch (Exception e) {}

                    PftypeBO pftypeBO = null;


                    pftypeBO = fkblService.gettype(FkdlShjg.getLoanStatus(), "loanStatus");
                    if (pftypeBO != null) FkdlShjg.setLoanStatus(pftypeBO.getType());
                    if (FkdlShjg.getEtrdLnIntRt() == null) {
                        FkdlShjg.setEtrdLnIntRt(0.00);
                    }
                    if (FkdlShjg.getDrwngAmt() == null) {
                        FkdlShjg.setDrwngAmt(0.00);
                    }
                    //System.out.println(FkdlShjg);
                    String fkjl=fkblService.add_notifiy_loan(FkdlShjg);
                    //更新上银的订单状态
                    paramLogger.info(String.format("更新上银保理，付款单号:%s,订单状态:%s",FkdlShjg.getApplyNo(),FkdlShjg.getLoanStatus()));
                    Integer i = fkblService.updateshbank_OrdrRgst_checkstate(FkdlShjg.getOrderSeqNo(),  FkdlShjg.getLoanStatus(),"");
                    System.out.println(i);

                   // paramLogger.info(fkjl);
                    if (!StringUtils.isBlank(FkdlShjg.getApplyNo())) {
                        ApplyPaymentDTO applyPaymentDTO = new ApplyPaymentDTO();
                        applyPaymentDTO.setBankzt("已融资");
                        applyPaymentDTO.setApplyNo(FkdlShjg.getApplyNo());
                        Integer updatecount=fkblService.update_applypayment_fkzt(applyPaymentDTO);
                        paramLogger.info(String.format("更新付款申请，付款单号:%s,融资状态:%s",FkdlShjg.getApplyNo(),"已融资"));
                    }
                    paramLogger.info(fkjl);
                }
            }

            return ret;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("error-->" + msg, e);
            ResultDTO ret1 = new ResultDTO(requestId, ErrorMessage.ERR_DEAL_BUSINESS, ErrorMessage.ERROR);
            ret = HttpUtil.encode_key(CHANNEL,ret1, false, false, "", UUID.randomUUID().toString());
            return ret;
        } finally {
            paramLogger.info("out-->" + ret);
        }
    }



}
